﻿using System;
using System.IO;
using System.Windows.Media;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace Oxage.CNC
{
	public class Helper
	{
		#region Colors
		/// <summary>
		/// Converts a hex color string to a System.Windows.Media.Color.
		/// </summary>
		/// <param name="hex">Color string formatted as #[AA]RRGGBB, e.g. "#FF7F7F7F", "#7F7F7F".</param>
		/// <returns>Returns a color defined by input string or black color if the string cannot be parsed properly.</returns>
		public static Color GetColor(string hex)
		{
			byte a = 0xFF, r = 0x00, g = 0x00, b = 0x00;

			if (!string.IsNullOrEmpty(hex) && hex[0] == '#')
			{
				hex = hex.Substring(1);
				if (hex.Length == 8)
				{
					a = Convert.ToByte(hex.Substring(0, 2), 16);
					r = Convert.ToByte(hex.Substring(2, 2), 16);
					g = Convert.ToByte(hex.Substring(4, 2), 16);
					b = Convert.ToByte(hex.Substring(6, 2), 16);
				}
				else if (hex.Length >= 6)
				{
					a = 0xFF;
					r = Convert.ToByte(hex.Substring(0, 2), 16);
					g = Convert.ToByte(hex.Substring(2, 2), 16);
					b = Convert.ToByte(hex.Substring(4, 2), 16);
				}
			}

			return Color.FromArgb(a, r, g, b);
		}

		/// <summary>
		/// Converts a hex color string to a System.Windows.Media.SolidColorBrush.
		/// </summary>
		/// <param name="hex">Color string formatted as #[AA]RRGGBB, e.g. "#FF7F7F7F", "#7F7F7F".</param>
		/// <returns></returns>
		public static Brush GetBrush(string hex)
		{
			return new SolidColorBrush(GetColor(hex));
		}
		#endregion

		#region Serialization
		public static string JsonSerialize(object json)
		{
			return JsonConvert.SerializeObject(json);
		}

		public static object JsonDeserialize(string json)
		{
			return JsonConvert.DeserializeObject(json);
		}

		public static T JsonDeserialize<T>(string json)
		{
			//How to use: http://james.newtonking.com/projects/json-net.aspx
			return JsonConvert.DeserializeObject<T>(json);
		}

		public static byte[] BsonSerialize(object obj)
		{
			//Serialize to BSON bytes
			//Reference: http://james.newtonking.com/archive/2009/12/26/json-net-3-5-release-6-binary-json-bson-support.aspx
			byte[] data = null;
			using (MemoryStream ms = new MemoryStream())
			{
				JsonSerializer serializer = new JsonSerializer();
				BsonWriter writer = new BsonWriter(ms);
				serializer.Serialize(writer, obj);
				data = ms.ToArray();
			}
			return data;
		}

		public static object BsonDeserialize(byte[] data)
		{
			return BsonDeserialize<object>(data);
		}

		public static T BsonDeserialize<T>(byte[] data)
		{
			T result = default(T);
			using (MemoryStream ms = new MemoryStream())
			{
				JsonSerializer serializer = new JsonSerializer();
				ms.Write(data, 0, data.Length);
				BsonReader reader = new BsonReader(ms);
				result = serializer.Deserialize<T>(reader);
			}
			return result;
		}
		#endregion
	}
}
